package org.zwy.gradetrack.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.zwy.gradetrack.entity.Major;
import org.zwy.gradetrack.entity.Teacher;
import org.zwy.gradetrack.mapper.TeacherMapper;
import org.zwy.gradetrack.service.MajorService;
import org.zwy.gradetrack.service.TeacherService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 教师服务实现类
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {

    @Autowired
    private MajorService majorService;

    @Override
    public Page<Teacher> pageTeachers(Integer current, Integer size, String name, String teacherId, String title, Integer majorId) {
        LambdaQueryWrapper<Teacher> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(name)) {
            wrapper.like(Teacher::getName, name);
        }
        if (StringUtils.hasText(teacherId)) {
            wrapper.eq(Teacher::getTeacherId, teacherId);
        }
        if (StringUtils.hasText(title)) {
            wrapper.like(Teacher::getTitle, title);
        }
        if (majorId != null) {
            wrapper.eq(Teacher::getMajorId, majorId);
        }
        wrapper.orderByDesc(Teacher::getCreateTime);
        return page(new Page<>(current, size), wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createTeacher(Teacher teacher) {
        // 检查教师工号是否已存在
        LambdaQueryWrapper<Teacher> teacherIdWrapper = new LambdaQueryWrapper<>();
        teacherIdWrapper.eq(Teacher::getTeacherId, teacher.getTeacherId());
        if (count(teacherIdWrapper) > 0) {
            throw new RuntimeException("教师工号已存在");
        }

        // 检查所属专业是否存在
        if (teacher.getMajorId() != null) {
            Major major = majorService.getById(teacher.getMajorId());
            if (major == null) {
                throw new RuntimeException("所属专业不存在");
            }
        }

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        teacher.setCreateTime(now);
        teacher.setUpdateTime(now);

        return save(teacher);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTeacher(Teacher teacher) {
        // 检查教师是否存在
        Teacher existingTeacher = getById(teacher.getId());
        if (existingTeacher == null) {
            throw new RuntimeException("教师不存在");
        }

        // 检查教师工号是否与其他教师重复
        if (!existingTeacher.getTeacherId().equals(teacher.getTeacherId())) {
            LambdaQueryWrapper<Teacher> teacherIdWrapper = new LambdaQueryWrapper<>();
            teacherIdWrapper.eq(Teacher::getTeacherId, teacher.getTeacherId())
                            .ne(Teacher::getId, teacher.getId());
            if (count(teacherIdWrapper) > 0) {
                throw new RuntimeException("教师工号已存在");
            }
        }

        // 检查所属专业是否存在
        if (teacher.getMajorId() != null) {
            Major major = majorService.getById(teacher.getMajorId());
            if (major == null) {
                throw new RuntimeException("所属专业不存在");
            }
        }

        // 设置更新时间
        teacher.setUpdateTime(LocalDateTime.now());

        return updateById(teacher);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteTeacher(Integer id) {
        // 检查教师是否存在
        if (getById(id) == null) {
            throw new RuntimeException("教师不存在");
        }
        return removeById(id);
    }

    @Override
    public Teacher getTeacherById(Integer id) {
        Teacher teacher = getById(id);
        if (teacher == null) {
            throw new RuntimeException("教师不存在");
        }
        return teacher;
    }

    @Override
    public List<Teacher> getTeachersByName(String name) {
        LambdaQueryWrapper<Teacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Teacher::getName, name);
        wrapper.orderByDesc(Teacher::getCreateTime);
        return list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchImport(List<Teacher> teachers) {
        if (teachers == null || teachers.isEmpty()) {
            throw new RuntimeException("导入数据不能为空");
        }

        // 检查教师工号是否重复
        Set<String> existingTeacherIds = list().stream()
                .map(Teacher::getTeacherId)
                .collect(Collectors.toSet());

        for (Teacher teacher : teachers) {
            if (existingTeacherIds.contains(teacher.getTeacherId())) {
                throw new RuntimeException("教师工号已存在：" + teacher.getTeacherId());
            }
            // 检查所属专业是否存在
            if (teacher.getMajorId() != null) {
                Major major = majorService.getById(teacher.getMajorId());
                if (major == null) {
                    throw new RuntimeException("所属专业不存在：ID " + teacher.getMajorId());
                }
            }
        }

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        teachers.forEach(teacher -> {
            teacher.setCreateTime(now);
            teacher.setUpdateTime(now);
        });

        return saveBatch(teachers);
    }

    @Override
    public List<Teacher> getAllTeachers() {
        return list(new LambdaQueryWrapper<Teacher>().orderByDesc(Teacher::getCreateTime));
    }
} 